package com.qdaily.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.qdaily.supportlibrary.app.FragmentParam;
import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.request.RequestCacheManager;
import com.qdaily.supportlibrary.updateapp.CheckVersionService;
import com.qdaily.supportlibrary.updateapp.UpdateHandler;
import com.qdaily.supportlibrary.util.NetUtil;
import com.qdaily.supportlibrary.util.QDJsonUtil;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.controller.ActivityController;
import com.qdaily.ui.data.Constants;
import com.qdaily.ui.data.QDConfigConstants;
import com.qdaily.ui.data.UserInformation;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.entity.HomeLeftSiderEntity;
import com.qdaily.ui.net.entity.RadarEntity;
import com.qdaily.ui.net.model.RadarFeeds;
import com.qdaily.ui.ui.fragment.MainFragment;
import com.qdaily.ui.ui.views.DrawerArrowDrawable;
import com.qdaily.ui.ui.views.GuideDialog;
import com.qdaily.ui.ui.views.SidebarController;
import com.qdaily.ui.ui.views.radar.TitleValueEntity;
import com.qdaily.ui.util.BusProvider;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页
 * * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 3/30/15
 * Time: 13:47
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class MainActivity extends QDBaseActivity implements
        View.OnClickListener,
        DrawerLayout.DrawerListener {

    private DrawerLayout mDrawerLayout;
    private SidebarController sidebarController;

    private DrawerArrowDrawable drawerArrowDrawable;
    private FrameLayout.LayoutParams layoutParams;
    private int sideBarWidth;
    private int drawerWidth;
    private int drawerMarginLeft;
    private FrameLayout content_frame;
    private FrameLayout sidebar_btn_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViewRes();

        getRequestManager().requestHomesLeftSidebar();
        getRequestManager().requestRadar();

        pushFragmentToBackStack(MainFragment.class, null);

        //http cache status
        QLog.d("getFileCachePath=" + RequestCacheManager.getInstance().getFileCachePath() + "\n" +
                "getFileCacheMaxSpace=" + RequestCacheManager.getInstance().getFileCacheMaxSpace() / 1024f + "KB" + "\n" +
                "getFileCacheUsedSpace=" + RequestCacheManager.getInstance().getFileCacheUsedSpace() / 1024f + "KB" + "\n" +
                "getMemoryCacheMaxSpace=" + RequestCacheManager.getInstance().getMemoryCacheMaxSpace() / 1024f + "KB" + "\n" +
                "getMemoryCacheUsedSpace=" + RequestCacheManager.getInstance().getMemoryCacheUsedSpace() / 1024f + "KB");

        ActivityController.getInstance().displayJpushContent(this, getIntent());

    }

    @Override
    protected void onNewIntent(Intent intent) {
        ActivityController.getInstance().displayJpushContent(this, intent);
        super.onNewIntent(intent);
    }

    @Override
    protected int getFragmentContainerId() {
        return R.id.content_frame;
    }

    private void initViewRes() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerListener(this);
        sidebarController = (SidebarController) findViewById(R.id.sliderListController);
        drawerArrowDrawable = new DrawerArrowDrawable(this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };
        sidebar_btn_layout = (FrameLayout) this.findViewById(R.id.sidebar_btn_layout);
        ImageView sidebar_btn = (ImageView) this.findViewById(R.id.main_sidebar_btn);
        sidebar_btn.setImageDrawable(drawerArrowDrawable);
        sidebar_btn.setOnClickListener(this);
        drawerArrowDrawable.setColor(R.color.ldrawer_color);
        drawerWidth = getResources().getDimensionPixelOffset(R.dimen.ldrawer_width);
        layoutParams = new FrameLayout.LayoutParams(drawerWidth, drawerWidth);
        drawerMarginLeft = getResources().getDimensionPixelOffset(R.dimen.ldrawer_marginBottom);

        content_frame = (FrameLayout) this.findViewById(R.id.content_frame);
        content_frame.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                content_frame.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int height = content_frame.getMeasuredHeight();
                layoutParams.setMargins(drawerMarginLeft, height - drawerWidth - drawerMarginLeft, 0, 0);
                sidebar_btn_layout.setLayoutParams(layoutParams);
            }
        });

        if (QDApplication.isDebugMode && !BuildConfig.DEBUG) {
            new CheckVersionService(this, new UpdateHandler(this, getString(R.string.app_name)), Constants.AUTO_UPDATE).start();
        }

        if (!getQDConfigManager().getBoolean(QDConfigConstants.KEY_MAIN_GUIDE_IS_SHOW, false)) {
            GuideDialog guideDialog = new GuideDialog(this);
            guideDialog.displayHomeGuide();
            guideDialog.show();
            getQDConfigManager().saveBoolean(QDConfigConstants.KEY_MAIN_GUIDE_IS_SHOW, true);
        }
    }

    public void closeDrawers() {
        mDrawerLayout.closeDrawers();
    }

    //登录注册成功以后，调用此方法。
    @Subscribe
    public void onUpdateUserInfo(UserInformation userInformation) {
        sidebarController.onUpdateUserInfo(userInformation);
    }

    //注销
    @Subscribe
    public void logoutUpdateUi(String Logout) {
        sidebarController.logoutUpdateUi();
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        super.onRequestCallBack(params, response);

        if (params instanceof NetConfigs.RequestHomeLeftSidebar) {
            HomeLeftSiderEntity h = QDJsonUtil.Json2Object(response.toString(), HomeLeftSiderEntity.class);

            sidebarController.displaySources(h.getResponse());
        }

        if (params instanceof NetConfigs.RequestRadar) {
            RadarEntity radarEntity = QDJsonUtil.Json2Object(response.toString(), RadarEntity.class);
            if (radarEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200 &&
                    null != radarEntity.getResponse() && radarEntity.getResponse().size() > 0) {
                updateRadar(radarEntity);
            }
        }
    }

    private void updateRadar(RadarEntity radarEntity) {
        List<TitleValueEntity> data = new ArrayList<>();
        for (int i = 0; i < radarEntity.getResponse().size(); i++) {
            RadarFeeds radarFeeds = radarEntity.getResponse().get(i);
            data.add(new TitleValueEntity(radarFeeds.getTitle(), radarFeeds.getValue() * 10f, radarFeeds.getId()));
        }
        sidebarController.updateRadar(data);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.main_sidebar_btn) {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    @Override
    public void onDrawerSlide(View view, float v) {
        if (sideBarWidth == 0) {
            sideBarWidth = view.getMeasuredWidth();
        }
        int x = (int) (sideBarWidth * v);
        layoutParams.setMargins(x + drawerMarginLeft, layoutParams.topMargin, 0, 0);
        sidebar_btn_layout.setLayoutParams(layoutParams);
        drawerArrowDrawable.setProgress(v);
    }

    @Override
    public void onDrawerOpened(View view) {
        getRequestManager().requestRadar();

        if (!getQDConfigManager().getBoolean(QDConfigConstants.KEY_SIDEBAR_GUIDE_IS_SHOW, false)) {
            GuideDialog guideDialog = new GuideDialog(this);
            guideDialog.displaySidebarGuide();
            guideDialog.show();
            getQDConfigManager().saveBoolean(QDConfigConstants.KEY_SIDEBAR_GUIDE_IS_SHOW, true);
        }
    }

    @Override
    public void onDrawerClosed(View view) {
        layoutParams.setMargins(drawerMarginLeft, layoutParams.topMargin, 0, 0);
        sidebar_btn_layout.setLayoutParams(layoutParams);
        drawerArrowDrawable.setProgress(0);
    }

    @Override
    public void onDrawerStateChanged(int i) {
    }

    private boolean isSideBarBtnHide = false;

    private void hideSideBarBtn(boolean isHide) {
        if (isSideBarBtnHide != isHide) {
            isSideBarBtnHide = isHide;
            sidebar_btn_layout.setVisibility(isHide ? View.GONE : View.VISIBLE);
        }
    }

    public void onChildScrollStateChange(AbsListView view, int scrollState) {
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            hideSideBarBtn(false);
        }
    }

    public void onChildScroll(boolean scrollUp) {
        hideSideBarBtn(!scrollUp);
    }

    public SidebarController getSidebarController() {
        return sidebarController;
    }

    public void setSidebarController(SidebarController sidebarController) {
        this.sidebarController = sidebarController;
    }

    private long backTime;
    @Override
    public void onBackPressed() {
        if (!(mCurrentFragment instanceof MainFragment)) {
            mDrawerLayout.closeDrawer(Gravity.LEFT);
            goToFragment(MainFragment.class, null);
            BusProvider.getInstance().post(new MainFragment.DisplayFirstLabel());
            return;
        }

        long curTime = System.currentTimeMillis();
        if (curTime - backTime > 2000) {
            backTime = System.currentTimeMillis();
            displayToast(getCloseWarning());
            return;
        }
        ActivityController.getInstance().closeApp();
    }

    protected String getFragmentTag(FragmentParam param) {
        Object data = param.data;
        if (data == null)
        {
            return param.cls.toString();
        }
        else
        {
            return param.cls.toString() + param.data.toString();
        }
    }
}
